package 富婆梦.第一阶段.Java基础视频学习.Scoket知识点.TCP多线程上传图片;

import java.io.*;
import java.net.Socket;
import java.util.Random;

/**
 * @ProjectName: java-learning
 * @Package: 富婆梦.第一阶段.Scoket知识点.TCP多线程上传图片
 * @ClassName: Upload
 * @Author: hemengjin
 * @Description:
 * @Date:2021/11/11 13:58
 * @Version: 1.0
 */
public class Upload implements Runnable{
    Socket socket;
    public Upload(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            //创建File对象，要将读到的文件存在本地文件夹内
            File file = new File("C:\\Users\\18279\\Pictures\\Camera Roll");

            //防止文件同名被覆盖,从新定义文件名字
            //规则:  域名+毫秒值+6位随机数
            String fileName = "meng" + System.currentTimeMillis() + new Random().nextInt(99999) + ".jpg";

            FileOutputStream fileOutputStream = new FileOutputStream(file + "\\" + fileName);
            //读数据
            byte[] data = new byte[1024];
            while (inputStream.read(data) != -1) {
                fileOutputStream.write(data);
            }

            //读到数据之后，给客户端一个提示
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("我已经收到了！谢谢你哦~".getBytes());
            outputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
